// Methods related to roles

import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { Roles } from './roles.js';
const weight = 10;
//权限
Meteor.methods({
  'roles.insert'(name, weight) {
    return Roles.insert({
      name,
      weight,
      createdAt: new Date(),
    });
  },
  'roles.delete'(id) {

    return Roles.remove(id);
  },
  'roles.update'(id, name, weight) {
    

    return Roles.update(id, {
      $set: {
        name,
        weight,
      },
    });
  },
  'roles.permit'(weight){
    //判断当前用户的是否准入
    console.log(Meteor.user().isBanned);
     let role_ids = Meteor.user().role_ids;

    let hasMemberRole = false;

    let minWeight = 500;

    if (role_ids != undefined) {
    for (var i = 0; i < role_ids.length; i++) {
      let role = Roles.findOne({_id: role_ids[i]});
      if (role != undefined) {
        if (role.name == "网站成员") {
        hasMemberRole = true;
        }
        if (role.weight <= minWeight) {
          minWeight = role.weight;//用户所包含的角色中找出最小权重
        }
      }
      
    }
    }else{
      role_ids = new Array();
    }

    if (!hasMemberRole) {//务必保证每个用户都有网站成员这个角色
      let memberRoles = Roles.find({name: "网站成员"});
      console.log(memberRoles.fetch());
      if (memberRoles.count() == 0) {
        let memberId = Roles.insert({
            name: "网站成员",
            weight: 500,
            createdAt: new Date(),
          });
          role_ids.push(memberId);
      }else{
        role_ids.push(memberRoles.fetch()[0]._id);
      }

          
      Meteor.users.update(Meteor.userId(), {
        $set: {
          role_ids: role_ids,
        }
      });
        }
      
      if (Meteor.user().isBanned) {
        return false;
      }
      if (minWeight <= weight) {
        return true;
      }
      return false;
    }
});
